<template>
  <div class="order-review">
    <!-- 评价统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总评价数</span>
            </div>
          </template>
          <div class="statistics-value">{{ statistics.totalCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>好评率</span>
            </div>
          </template>
          <div class="statistics-value">{{ statistics.goodRate }}%</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>平均评分</span>
            </div>
          </template>
          <div class="statistics-value">{{ statistics.averageScore }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待回复</span>
            </div>
          </template>
          <div class="statistics-value">{{ statistics.pendingReplyCount }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="评分">
          <el-select v-model="searchForm.score" placeholder="请选择评分" clearable>
            <el-option label="5星" :value="5" />
            <el-option label="4星" :value="4" />
            <el-option label="3星" :value="3" />
            <el-option label="2星" :value="2" />
            <el-option label="1星" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="评价时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="回复状态">
          <el-select v-model="searchForm.replyStatus" placeholder="请选择状态" clearable>
            <el-option label="已回复" value="replied" />
            <el-option label="未回复" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleExport">导出评价</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 评价列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="orderNo" label="订单编号" min-width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="score" label="评分" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.score"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评价内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="images" label="评价图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.images && row.images.length"
              :src="row.images[0]"
              :preview-src-list="row.images"
              fit="cover"
              class="review-image"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="评价时间" width="180" />
        <el-table-column prop="replyContent" label="商家回复" min-width="200" show-overflow-tooltip />
        <el-table-column prop="replyTime" label="回复时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="!row.replyContent"
              type="primary"
              link
              @click="handleReply(row)"
            >
              回复
            </el-button>
            <el-button
              v-else
              type="primary"
              link
              @click="handleEditReply(row)"
            >
              修改回复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialog.visible"
      :title="replyDialog.isEdit ? '修改回复' : '回复评价'"
      width="500px"
    >
      <el-form
        ref="replyFormRef"
        :model="replyDialog.form"
        :rules="replyDialog.rules"
        label-width="80px"
      >
        <el-form-item label="评价内容">
          <div class="review-content">
            <div class="review-score">
              <el-rate v-model="replyDialog.review.score" disabled />
              <span class="score-text">{{ replyDialog.review.score }}分</span>
            </div>
            <div class="review-text">{{ replyDialog.review.content }}</div>
            <div v-if="replyDialog.review.images?.length" class="review-images">
              <el-image
                v-for="(img, index) in replyDialog.review.images"
                :key="index"
                :src="img"
                :preview-src-list="replyDialog.review.images"
                fit="cover"
                class="review-image"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="回复内容" prop="content">
          <el-input
            v-model="replyDialog.form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getMerchantOrderReviews,
  replyMerchantOrderReview,
  getMerchantReviewStatistics,
  exportMerchantReviews
} from '@/api/merchant'

// 统计数据
const statistics = reactive({
  totalCount: 0,
  goodRate: 0,
  averageScore: 0,
  pendingReplyCount: 0
})

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  score: '',
  dateRange: [],
  replyStatus: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 回复对话框
const replyDialog = reactive({
  visible: false,
  isEdit: false,
  review: {},
  form: {
    content: ''
  },
  rules: {
    content: [
      { required: true, message: '请输入回复内容', trigger: 'blur' },
      { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
    ]
  }
})

const replyFormRef = ref(null)

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantReviewStatistics()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取评价统计数据失败:', error)
  }
}

// 获取评价列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderReviews({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    })
    tableData.value = data.list
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取评价列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 导出评价
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    const response = await exportMerchantReviews(params)
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `订单评价列表_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    ElMessage.error('导出评价失败')
  }
}

// 回复评价
const handleReply = (row) => {
  replyDialog.isEdit = false
  replyDialog.review = row
  replyDialog.form.content = ''
  replyDialog.visible = true
}

// 修改回复
const handleEditReply = (row) => {
  replyDialog.isEdit = true
  replyDialog.review = row
  replyDialog.form.content = row.replyContent
  replyDialog.visible = true
}

// 提交回复
const submitReply = async () => {
  if (!replyFormRef.value) return
  
  try {
    await replyFormRef.value.validate()
    await replyMerchantOrderReview(replyDialog.review.id, {
      content: replyDialog.form.content
    })
    ElMessage.success(replyDialog.isEdit ? '修改回复成功' : '回复成功')
    replyDialog.visible = false
    getList()
    getStatistics()
  } catch (error) {
    console.error('提交回复失败:', error)
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getStatistics()
  getList()
})
</script>

<style lang="scss" scoped>
.order-review {
  .statistics-cards {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .statistics-value {
      font-size: 24px;
      font-weight: bold;
      color: #409EFF;
      text-align: center;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .review-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
    }
  }
  
  .review-content {
    .review-score {
      margin-bottom: 10px;
      
      .score-text {
        margin-left: 10px;
        color: #ff9900;
      }
    }
    
    .review-text {
      margin-bottom: 10px;
      color: #606266;
    }
    
    .review-images {
      display: flex;
      gap: 10px;
      
      .review-image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 